package com.wonders.utils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
/**
 * 功能描述:使用redis生成全局唯一ID
 * @Author: yyalin
 * @CreateDate: 2023/8/13 11:35
 */
@Component
public class RedisIdUtils {
    //预生成开始时间戳
    private static final long BEGIN_TIMESTAMP = 1640995200L;
    //序列号的位数
    private static final int COUNT_BITS = 32;
    //redis提供的字符串
    private StringRedisTemplate stringRedisTemplate;
    //有参构造函数
    public RedisIdUtils(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    /**
     * 功能描述:根据keyPrefix前缀生成对应业务的全局唯一ID
     * @MethodName: nextId
     * @MethodParam: [keyPrefix:使用前缀来区分不同的业务]
     * @Return: long
     * @Author: yyalin
     * @CreateDate: 2023/8/13 12:20
     */
    public long nextId(String keyPrefix) {
        // 1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;
        // 2.生成序列号
        // 2.1.获取当前日期，精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 2.2.自增长 icr:order:2023:08:13
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        // 3.拼接并返回  timestamp << COUNT_BITS ：向左移动32位
        //原本时间戳在低位上，通过向左移动32位，变位到高位存储，低32位都是0，然后与自增序列按位操作
        //形成低32位为序列号。
        return timestamp << COUNT_BITS | count;
    }
}
